package com.kgc.crowd.distributioncrowdprojectmanager.controller;

import com.alibaba.fastjson.JSON;
import com.kgc.crowd.distributioncrowdcommon.VO.MemberConfirmInfoVO;
import com.kgc.crowd.distributioncrowdcommon.VO.ProjectVO;
import com.kgc.crowd.distributioncrowdcommon.VO.ReturnVO;
import com.kgc.crowd.distributioncrowdcommon.VO.TagVO;
import com.kgc.crowd.distributioncrowdcommon.api.DataBaseOperationRemoteService;
import com.kgc.crowd.distributioncrowdcommon.api.RedisOperationRemoteService;
import com.kgc.crowd.distributioncrowdcommon.pojo.*;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdConstant;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/project/manager")
@RestController
public class ProjectController {
    @Resource
    RedisOperationRemoteService redisOperationRemoteService;

    @RequestMapping("/initCreation")
    public ResultEntity<ProjectVO> initCreation(
            @RequestParam("memberSignToken") String memberSignToken) {
        // 1.检查是否登录，也就是检查memberSignToken是否有效
        ResultEntity<String> resultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(memberSignToken);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)) {
            return ResultEntity.failed(resultEntity.getMessage());
        }
        String memberId = resultEntity.getData();
        if (memberId == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        // 2.创建空ProjectVO对象备用
        ProjectVO projectVO = new ProjectVO();
        // 3.将memberSignToken存入ProjectVO对象
        projectVO.setMemberSignToken(memberSignToken);
        // 4.将projectTempToken存入ProjectVO对象
        String projectTempToken = CrowdUtils.projectVOToken();
        projectVO.setProjectTempToken(projectTempToken);
        // 5.将ProjectVO对象转换成JSON
        String jsonString = JSON.toJSONString(projectVO);
        // 6.将projectTempToken和jsonString作为key、value存入Redis
        // 虽然是临时数据，但是不能指定一个固定的过期时间，在用户操作完成时删除
        ResultEntity<String> stringResultEntity = redisOperationRemoteService.saveNormalStringKeyValue(projectTempToken, jsonString, -1);
        if (stringResultEntity.getResult().equals(ResultEntity.FAILED)) {
            return ResultEntity.failed(stringResultEntity.getMessage());
        }
        return ResultEntity.successWithData(projectVO);
    }
    /**
     * 点击上传项目头图时调用
     * @param memberSignToken 登录成功时，生成的token
     * @param projectTempToken  项目初始化时，生成的token
     * @param headerPicturePath 图片上传成功后OSS上的图片路径
     * @return
     */
    @RequestMapping("/save/head/picture/path")
    public ResultEntity<String> saveHeadPicturePath(
            @RequestParam("memberSignToken") String memberSignToken,
            @RequestParam("projectTempToken") String projectTempToken,
            @RequestParam("headerPicturePath") String headerPicturePath
    ) {
        // 检查是否登录，也就是检查memberSignToken是否有效
        ResultEntity<String> resultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(memberSignToken);
        if(ResultEntity.FAILED.equals(resultEntity.getResult())) {
            return ResultEntity.failed(resultEntity.getMessage());
        }
        String memberId = resultEntity.getData();
        if(memberId == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        // project-manager工程访问Redis查询ProjectVO对象
        ResultEntity<String> stringResultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(projectTempToken);
        if(ResultEntity.FAILED.equals(stringResultEntity.getResult())) {
            return stringResultEntity;
        }
        // 从Redis查询到JSON字符串
        String projectVOJSON = stringResultEntity.getData();
        // 将JSON字符串还原成ProjectVO对象
        ProjectVO projectVO = JSON.parseObject(projectVOJSON, ProjectVO.class);
        // 将图片路径存入ProjectVO对象
        projectVO.setHeaderPicturePath(headerPicturePath);
        // 将ProjectVO对象转换为JSON字符串
        String jsonString = JSON.toJSONString(projectVO);
        // 将JSON字符串重新存入Redis
        return redisOperationRemoteService.saveNormalStringKeyValue(projectTempToken, jsonString, -1);
    }
    /**
     * 点击项目详情图片上传时调用
     * @param memberSignToken
     * @param projectTempToken
     * @param detailPicturePathList
     * @return
     */
    @RequestMapping("/save/detail/picture/path/list")
    public ResultEntity<String> saveDetailPicturePathList(
            @RequestParam("memberSignToken") String memberSignToken,
            @RequestParam("projectTempToken") String projectTempToken,
            @RequestParam("detailPicturePathList") List<String> detailPicturePathList
    ) {
// 检查是否登录，也就是检查memberSignToken是否有效
        ResultEntity<String> resultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(memberSignToken);
        if(ResultEntity.FAILED.equals(resultEntity.getResult())) {
            return ResultEntity.failed(resultEntity.getMessage());
        }
        String memberId = resultEntity.getData();
        if(memberId == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        // project-manager工程访问Redis查询ProjectVO对象
        ResultEntity<String> stringResultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(projectTempToken);
        if(ResultEntity.FAILED.equals(stringResultEntity.getResult())) {
            return stringResultEntity;
        }
        // 从Redis查询到JSON字符串
        String projectVOJSON = stringResultEntity.getData();
        // 将JSON字符串还原成ProjectVO对象
        ProjectVO projectVO = JSON.parseObject(projectVOJSON, ProjectVO.class);
        // 将图片路径存入ProjectVO对象
        projectVO.setDetailPicturePathList(detailPicturePathList);
        // 将ProjectVO对象转换为JSON字符串
        String jsonString = JSON.toJSONString(projectVO);
        // 将JSON字符串重新存入Redis
        return redisOperationRemoteService.saveNormalStringKeyValue(projectTempToken, jsonString, -1);
    }

    /**
     * 添加项目时点击下一步时，调用
     * @param projectVOFront
     * @return
     */
    @RequestMapping("/save/project/information")
    public ResultEntity<String> saveProjectInformation(@RequestBody ProjectVO projectVOFront) {
        // 获取memberSignToken
        String memberSignToken = projectVOFront.getMemberSignToken();
        // 检查是否登录，也就是检查memberSignToken是否有效
        ResultEntity<String> resultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(memberSignToken);
        if(ResultEntity.FAILED.equals(resultEntity.getResult())) {
            return ResultEntity.failed(resultEntity.getMessage());
        }
        String memberId = resultEntity.getData();
        if(memberId == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }

        // 从projectVOFront中获取projectTempToken
        String projectTempToken = projectVOFront.getProjectTempToken();
        // project-manager工程访问Redis查询ProjectVO对象
        ResultEntity<String> resultEntityForGetValue = redisOperationRemoteService.retrieveStringValueByStringKey(projectTempToken);

        if(ResultEntity.FAILED.equals(resultEntityForGetValue.getResult())) {
            return resultEntityForGetValue;
        }

        // 从Redis查询到JSON字符串
        String projectVOJSON = resultEntityForGetValue.getData();

        // 将JSON字符串还原成ProjectVO对象
        ProjectVO projectVOBehind = JSON.parseObject(projectVOJSON, ProjectVO.class);

        // 将projectVOBehind对象中头图和详情图复制到projectVOFront对象
        projectVOFront.setHeaderPicturePath(projectVOBehind.getHeaderPicturePath());
        projectVOFront.setDetailPicturePathList(projectVOBehind.getDetailPicturePathList());


        // 将projectVOBehind对象转换为JSON字符串
        String jsonString = JSON.toJSONString(projectVOFront);

        // 将JSON字符串重新存入Redis
        return redisOperationRemoteService.saveNormalStringKeyValue(projectTempToken, jsonString, -1);
    }
    /**
     * 当在回报设置点击下一步调用
     * @param returnVO
     * @return
     */
    @RequestMapping("/save/return/vo")
    public ResultEntity<String> saveReturnVO(@RequestBody ReturnVO returnVO) {
        // 1.检查memberSignToken确认用户是否登录
        String memberSignToken = returnVO.getMemberSignToken();
        // 检查是否登录，也就是检查memberSignToken是否有效
        ResultEntity<String> resultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(memberSignToken);
        if(ResultEntity.FAILED.equals(resultEntity.getResult())) {
            return ResultEntity.failed(resultEntity.getMessage());
        }
        String memberId = resultEntity.getData();
        if(memberId == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }

        // 2.根据projectTempToken查询ProjectVO对象
        String projectTempToken = returnVO.getProjectTempToken();

        ResultEntity<String> retrieveStringValueResultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(projectTempToken);

        if(ResultEntity.FAILED.equals(retrieveStringValueResultEntity.getResult())) {
            return retrieveStringValueResultEntity;
        }

        String json = retrieveStringValueResultEntity.getData();

        // 3.将JSON字符串还原成ProjectVO对象
        ProjectVO projectVO = JSON.parseObject(json, ProjectVO.class);

        // 4.获取之前存储过的ReturnVO的List
        List<ReturnVO> returnVOList = projectVO.getReturnVOList();

        // 5.如果returnVOList不是有效集合，则进行初始化
        if(!CrowdUtils.collectionEffectiveCheck(returnVOList)) {

            // ①创建集合对象
            returnVOList = new ArrayList<>();

            // ②将集合对象存入projectVO
            projectVO.setReturnVOList(returnVOList);
        }
        // 6.将当前ReturnVO存入returnVOList
        returnVOList.add(returnVO);

        // 7.将ProjectVO转换为JSON字符串
        String newJsonProject = JSON.toJSONString(projectVO);

        // 8.存入Redis
        return redisOperationRemoteService.saveNormalStringKeyValue(projectTempToken, newJsonProject,-1);
    }
    /**
     * 在确认信息时点击下一步
     * @param memberConfirmInfoVO
     * @return
     */
    @RequestMapping("/save/member/confirm/info/vo")
    public ResultEntity<String> saveMemberConfirmInfoVO(@RequestBody MemberConfirmInfoVO memberConfirmInfoVO) {
        // 1.检查memberSignToken确认用户是否登录
        String memberSignToken = memberConfirmInfoVO.getMemberSignToken();
        // 检查是否登录，也就是检查memberSignToken是否有效
        ResultEntity<String> resultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(memberSignToken);
        if(ResultEntity.FAILED.equals(resultEntity.getResult())) {
            return ResultEntity.failed(resultEntity.getMessage());
        }
        String memberId = resultEntity.getData();
        if(memberId == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }

        // 2.根据projectTempToken查询ProjectVO对象
        String projectTempToken = memberConfirmInfoVO.getProjectTempToken();

        ResultEntity<String> retrieveStringValueResultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(projectTempToken);

        if(ResultEntity.FAILED.equals(retrieveStringValueResultEntity.getResult())) {
            return retrieveStringValueResultEntity;
        }

        String json = retrieveStringValueResultEntity.getData();

        // 3.将JSON字符串还原成ProjectVO对象
        ProjectVO projectVO = JSON.parseObject(json, ProjectVO.class);

        //4.存入memberConfirmInfoVO对象
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        // 5.将ProjectVO转换为JSON字符串
        String newJsonProject = JSON.toJSONString(projectVO);

        // 6.存入Redis
        return redisOperationRemoteService.saveNormalStringKeyValue(projectTempToken, newJsonProject,-1);
    }

    @Resource
    DataBaseOperationRemoteService dataBaseOperationRemoteService;

    /**
     * 把数据保存到数据库
     * @param memberSignToken 登录成功后的token
     * @param projectTempToken redis中临时保存ProjectVO的键
     * @return
     */
    @RequestMapping("/save/whole/project")
    public ResultEntity<String> saveWholeProject(
            @RequestParam("memberSignToken") String memberSignToken,
            @RequestParam("projectTempToken") String projectTempToken) {
        // 检查是否登录，也就是检查memberSignToken是否有效
        ResultEntity<String> resultEntity = redisOperationRemoteService.retrieveStringValueByStringKey(memberSignToken);
        if (ResultEntity.FAILED.equals(resultEntity.getResult())) {
            return resultEntity;
        }

        String memberId = resultEntity.getData();

        if (memberId == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }

        // project-manager工程访问Redis查询ProjectVO对象
        ResultEntity<String> resultEntityForGetValue = redisOperationRemoteService
                .retrieveStringValueByStringKey(projectTempToken);

        if (ResultEntity.FAILED.equals(resultEntityForGetValue.getResult())) {
            return ResultEntity.failed(resultEntityForGetValue.getMessage());
        }

        // 从Redis查询到JSON字符串
        String projectVOJSON = resultEntityForGetValue.getData();

        // 将JSON字符串还原成ProjectVO对象
        ProjectVO projectVO = JSON.parseObject(projectVOJSON, ProjectVO.class);

        // 执行保存
        ResultEntity<String> resultEntityForSave = dataBaseOperationRemoteService.saveProjectRemote(projectVO, memberId);

        if(ResultEntity.FAILED.equals(resultEntityForSave.getResult())) {
            return resultEntityForSave;
        }

        // 删除Redis中的临时数据
        return redisOperationRemoteService.removeByKey(projectTempToken);
//        return resultEntity;
    }
    //查询所有类型
    @RequestMapping("/select/all/type")
    public ResultEntity<List<TypePO>> selectAllType(){
        return dataBaseOperationRemoteService.selectAllType();
    }

    //查询所有标签
    @RequestMapping("/select/all/tag")
    public ResultEntity<List<TagVO>> selectAllTag(){
        ResultEntity<List<TagPO>> listResultEntity = dataBaseOperationRemoteService.selectAllTag();
        //将所有数据存放到map中
        Map<Integer,TagVO> map=new HashMap<>();
        for (TagPO tagPO : listResultEntity.getData()) {
            TagVO tagVO=new TagVO(tagPO.getId(),tagPO.getPid(),tagPO.getName());
                map.put(tagVO.getId(),tagVO);
        }
        //循环map并为父节点添加子节点
        for (TagVO tagVO : map.values()) {
            //判断是否子节点
            if(tagVO.getPid()!=null){
                map.get(tagVO.getPid()).getChildrens().add(tagVO);
            }
        }
        List<TagVO> list=new ArrayList<>();
        //将父节点存放到list中
        for (TagVO tagVO : map.values()) {
            if(tagVO.getPid()==null){
                list.add(tagVO);
            }
        }
        return ResultEntity.successWithData(list);

    }

    @RequestMapping("/select/project")
    public ResultEntity<List<ProjectPO>> selectProject(){
        return dataBaseOperationRemoteService.selectProject();
    }
    @RequestMapping("/select/projectitempic")
    public ResultEntity<List<ProjectItemPicPO>> selectProjectItemPic(@RequestParam("projectid") Integer projectid){
        return dataBaseOperationRemoteService.selectProjectItemPic(projectid);
    }
    @RequestMapping("/select/return")
    public ResultEntity<List<ReturnPO>> selectReturnPo(){
        return dataBaseOperationRemoteService.selectReturnPo();
    }
    @RequestMapping("/selectProjectById")
    public ProjectPO selectProjectById(@RequestParam("id") Integer id){
        ProjectPO po = dataBaseOperationRemoteService.selectProjectById(id);
        return po;
    }
}